import * as dotenv from "dotenv";
import * as fs from "fs";
import * as Joi from "joi";

export interface EnvConfig{
    [prop:string]:string;
}

export class ConfigService{
    private readonly envConfig:EnvConfig;

    constructor(filePath:string){
        const config = dotenv.parse(fs.readFileSync(filePath));
        this.envConfig = this.validateInput(config);
    }

    private validateInput(envConfig:EnvConfig){
        const envVarsSchema:Joi.ObjectSchma = Joi.object({
            NODE_ENV:Joi.string().valid(['development','production','test','local']).default('development'),
            DATABASE_TYPE:Joi.string().default('mysql'),//数据库类型
            DATABASE_HOST:Joi.string().default('localhost'),//数据库主机地址
            DATABASE_PORT:Joi.number().default(3306),//数据库端口
            DATABASE_USER:Joi.string().default('root'),//数据库用户
            DATABASE_PWD:Joi.string(),//数据库密码
            DATABASE_DB:Joi.string().required(),//数据库名称
            DATABASE_SYNCHRONIZE:Joi.boolean().default(false),//是否同步数据库表结构
            DATABASE_DROPSCHEMA:Joi.boolean().default(false),//每次启动是否删除数据库表重新创建
        })

        const {error,value:validateEnvConfig} = Joi.validate(
            envConfig,
            envVarsSchema,
        );

        if(error){
            throw new Error(`Config validation error: ${error.message} `);
        }

        return validateEnvConfig;
    }

    get env():string { return this.envConfig.NODE_ENV }

    get databaseType():string { return this.envConfig.DATABASE_TYPE }

    get databaseHost():string { return this.envConfig.DATABASE_HOST }

    get databasePort():string { return this.envConfig.DATABASE_PORT }

    get databasePassword():string { return this.envConfig.DATABASE_PWD }

    get databaseName():string { return this.envConfig.DATABASE_DB }

    get databaseUser():string { return this.envConfig.DATABASE_USER }

    get databaseSynchronize():string { return this.envConfig.DATABASE_SYNCHRONIZE }

    get databaseDropSchma():string { return this.envConfig.DATABASE_DROPSCHEMA }
}